import {isDingTalk, openDingTalkLink} from './DingTalkUtil';

/**
 * 获取url指定参数
 */
export const getUrlParam = (name: string): string | null => {
  return new URLSearchParams(location.search.slice(1)).get(name);
};

/**
 * 获取url全部参数
 */
export const getUrlParams = (): URLSearchParams => {
  return new URLSearchParams(location.search.slice(1));
};

/**
 * 更新url参数
 * @param newParams
 */
export const updateUrlParams=(newParams: { [key: string]: string })=> {
  const currentUrl = new URL(window.location.href);
  Object.keys(newParams).forEach(key => {
    currentUrl.searchParams.set(key, newParams[key]);
  });
  window.history.replaceState({ path: currentUrl.toString() }, '', currentUrl.toString());
}

/**
 * 清除url参数
 */
export const clearUrlParams = () => {
  const currentUrl = new URL(window.location.href);
  currentUrl.search = ''; // 清除所有查询参数
  window.history.replaceState({path: currentUrl.toString()}, '', currentUrl.toString());
};

/**
 * 获取字符串地址的参数
 * @param search ?formId=1856524396700598272&viewType=view&isFlow=false
 */
export const getSearchObject = (search: string) => {
  const searchParams = new URLSearchParams(search);
  // 将查询参数转换为对象
  const searchObject: Record<string, string> = {};
  searchParams.forEach((value, key) => {
    searchObject[key] = value;
  });
  return searchObject;
};

/**
 * 组装字符串地址参数
 */
export const getSearchString = (searchObject: Record<string, string>) => {
  const searchParams = new URLSearchParams(searchObject);
  return searchParams.toString();
};
/**
 * 包裹url
 * @param url
 * @param hasHost 是否携带host  true携带 false不携带
 */
export const wrapUrl = (url: string,hasHost?:boolean): string => {
  //判断是否携带
  if (!hasHost) {
    url=`${window.location.origin}${url}`
  }
  //钉钉环境
  if (isDingTalk()) {
    return openDingTalkLink(url);
  }
  return url;
};


